var Q = require('q');

var redis = require('redis');
var redisClientSubscriber = redis.createClient();
var redisClientPublisher = redis.createClient();
var colors = require('colors');

var redisNameSpaceFromController = "DistMeasureManage:FromController"; //redis中的命名空间
var redisNameSpaceToController = "DistMeasureManage:ToController"; //redis中的命名空间

redisClientSubscriber.subscribe(redisNameSpaceFromController);

var bufferCaller = require('./bufferCaller');



var WebSocketServer = function() {
    var WebSocketServer = {
        WebClientList: [],
        tempData: [],
        Initial: function(expressServer) {

            var io = require('socket.io');
            var ioSocket = io.listen(expressServer, {
                'log': false
            });

            //向tspserver注册本客户
            redisClientSubscriber.on('message', function(channel, data) {
                console.log("From Redis: %s".green, data);
                var jsonData = JSON.parse(data);
                if (jsonData.Command === "Measure") {
                    var fn = (function(cmdData) {
                        return function() {
                            SendToAllClients(cmdData);
                        };
                    })(data);
                    bufferCaller.add(fn, "Dist");
                } else {
                    SendToAllClients(data);
                }
            });

            //发送数据给所有的在线网页用户
            function SendToAllClients(data) {

                for (var i = 0; i < WebSocketServer.WebClientList.length; i++) {
                    WebSocketServer.WebClientList[i].emit("DistMeasureManage", data);
                }
            }

            ioSocket.on('connection', function(socket) {
                console.log("New Client Connected!".green);
                //将socket推入维护列表
                WebSocketServer.WebClientList.push(socket);
                //侦听数据
                socket.on("DistMeasureManage", function(data) {
                    //这里的data是object而不是jsonStr
                    try {
                        if (data && data.Command) {
                            var dataStr = JSON.stringify(data);
                            redisClientPublisher.publish(redisNameSpaceToController, dataStr);
                            console.log("From WebSocket: %s".green, dataStr)
                        }
                    } catch (err) {
                        return;
                    }
                });
                socket.on('disconnect', (function(s) {
                    return function() {
                        console.log('One Client disconnected!');
                        var index = WebSocketServer.WebClientList.indexOf(s);
                        WebSocketServer.WebClientList.splice(index, 1);
                    };
                })(socket));
            });
        }
    };
    return WebSocketServer;
};

exports.WebSocketServer = WebSocketServer;
